import { ref, reactive, watch, onUnmounted } from "vue";
import { useDocumentVisibility } from "@vueuse/core";
import { useFullscreen } from '@vueuse/core';
import { ElMessageBox } from "element-plus";

export default function useFullscreenVisibility(fullRef, submit) {
	let stopWatch = false
	// 切屏次数
	const screenCutNum = ref(0)
	// 切换回来的时间限制
	const outTime = 1
	// window 切换计时
	const windowCutTime = ref(0);
	// visibility 计时
	const visibilityCutTime = ref(0);
	// 全屏计时
	const fullCutTime = ref(0);
	// visibility 离开页面-hidden  进入页面-visible
	const visibility = useDocumentVisibility();
	const { isFullscreen, enter, exit } = useFullscreen(fullRef);
	// 判断当前浏览器窗口是不是失去焦点
	window.onblur = () => {
		if (stopWatch) {
			return
		}
		// 离开全屏
		// 记住离开当前时间戳
		windowCutTime.value = new Date().getTime();

	}
	// 屏幕获得焦点
	window.onfocus = () => {
		if (stopWatch) {
			return
		}
		// 返回全屏
		if (!windowCutTime.value) {

			return
		}
		// 进来时间戳
		const currentTime = new Date().getTime();
		// 时间单位 s 
		const diff = (currentTime - windowCutTime.value) / 10;
		if (diff >= outTime) {
			// 切屏数量 + 1
			windowCutTime.value = 0
			screenCutNum.value += 1;
			console.log("🚀 ~ window.onfocus ~ screenCutNum.value:", screenCutNum.value)
		}
	}
	// 监听 visibility 
	const unwatch = watch(visibility, (current, previous) => {
		if (stopWatch) {
			return
		}
		if (current === "hidden") {
			// 记住离开当前时间戳
			visibilityCutTime.value = new Date().getTime();
		}
		if (current === "visible" && previous === "hidden") {
			if (!visibilityCutTime.value) {
				return
			}
			// 进来时间戳
			const currentTime = new Date().getTime();
			// 时间单位 s 
			const diff = (currentTime - visibilityCutTime.value) / 10;
			if (diff >= outTime) {
				// 切屏数量 + 1
				visibilityCutTime.value = 0
				screenCutNum.value += 1;
				console.log("🚀 ~ unwatch ~ screenCutNum.value:", screenCutNum.value)
			}
		}
	});
	const unFullwatch = watch(isFullscreen, value => {
		if (stopWatch) {
			return
		}
		if (!value) {
			// 离开全屏
			// 记住离开当前时间戳
			fullCutTime.value = new Date().getTime();
			ElMessageBox.confirm('退出全屏模式是为切屏一次，请问您是否交卷', '提示',
				{ confirmButtonText: '交卷', cancelButtonText: '继续答题', type: 'warning' }).
				then(() => {
					submit()
				}).catch(() => {
					enter()
				})
		} else {
			// 返回全屏
			if (!fullCutTime.value) {
				return
			}
			// 进来时间戳
			const currentTime = new Date().getTime();
			// 时间单位 s 
			const diff = (currentTime - fullCutTime.value) / 10;
			if (diff >= outTime) {
				// 切屏数量 + 1
				fullCutTime.value = 0
				screenCutNum.value += 1;
				console.log("🚀 ~ unFullwatch ~ screenCutNum.value:", screenCutNum.value)
			}
		}
	})
	onUnmounted(() => {
		unwatch();
		unFullwatch()
		window.onblur = null
		window.onfocus = null
	});
	const isStop = (value) => {
		stopWatch = value
		screenCutNum.value = 0;
		windowCutTime.value = 0;
		visibilityCutTime.value = 0;
		fullCutTime.value = 0;
	}
	return {
		screenCutNum, enter, exit, isStop
	}
}



